package com.fas.hehe.config.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.TreeMap;

import org.apache.commons.collections.CollectionUtils;

import com.fas.core.BaseService;
import com.fas.core.constant.R;
import com.fas.core.plugin.tree.jstree.Node;
import com.fas.core.util.sequence.Sequence;
import com.fas.hehe.config.model.Dictionary;

/**
 * 
 * 字典分类业务处理类
 *
 * @Copyright: Copyright (c) 2016 FAS
 * @anthor yixiaoping<thinker1013@163.com>
 * @since 2016年1月23日 下午1:59:59
 * @version V1.0
 */
public class DictionaryService extends BaseService {

	/**
	 * 
	 * @Title:一次性加载当前组织机构下面所有子机构，构建jstree插件树形结构对象列表
	 * @Description: 只查询状态为可用的
	 * @return     
	 * @anthor yixiaoping<thinker163@163.com>
	 * @date 2016年1月23日 下午2:09:46
	 */
	public List<Node> loadTreeOnceTime() {
		String sql = "select * from config_dictionary where FIND_IN_SET(id, queryChildrenDictionary(?)) and available = ? order by priority asc";
		List<Dictionary> list = Dictionary.dao.findByCache(R.CacheName.GLOBAL_DICT_DATA, R.Const.ROOT_DICTID,sql, R.Const.ROOT_DICTID,R.Dict.STATUS_AVAILABLE); // 后台根据父节点查询出的数据列表
		HashMap<Long, Dictionary> dictGroupMap = new HashMap<Long, Dictionary>();
		TreeMap<Long, List<Dictionary>> subDictGroupMap = new TreeMap<Long, List<Dictionary>>();
		for (Dictionary dictGroup : list) {
			Long id = dictGroup.getId();
			Long pid = dictGroup.getPid();

			if (id != R.Const.ROOT_DICTID) {
				List<Dictionary> subList = subDictGroupMap.get(pid);
				if (subList == null)
					subList = new ArrayList<Dictionary>();
				subList.add(dictGroup);
				subDictGroupMap.put(pid, subList);
			}
			dictGroupMap.put(id, dictGroup);
		}

		List<Node> nodeList = new ArrayList<Node>();
		Node rootNode = buildTreeNode(R.Const.ROOT_DICTID, subDictGroupMap, dictGroupMap);
		nodeList.add(rootNode);
		return nodeList;
	}

	/**
	 * 
	 * @Title:递归构建树jstree插件树形节点对象
	 * @Description: 
	 * @param parentId	
	 * 				当前节点ID
	 * @param subDictGroupMap
	 * 				{key: 字典类别编码Long,VALUE: 子节点列表List}
	 * @param dictGroupMap
	 * 				{key: 字典类别编码Long,VALUE: 字典类别 对象}
	 * @return     
	 * @anthor yixiaoping<thinker163@163.com>
	 * @date 2016年1月23日 下午2:09:12
	 */
	private Node buildTreeNode(Long parentId, TreeMap<Long, List<Dictionary>> subDictGroupMap,
			HashMap<Long, Dictionary> dictGroupMap) {
		List<Dictionary> subList = subDictGroupMap.get(parentId);
		Node node = new Node();

		Dictionary curGroup = dictGroupMap.get(parentId);
		Long groupId = curGroup.getId();
		String groupName = curGroup.getDictName();
		int dictType = curGroup.getDictType();
		String dictCode = curGroup.getDictCode();
		node.setId(groupId.toString());
		node.setText(groupName);
		node.addData("dictCode", dictCode);// 用户自定义数据
		node.setType(dictType + "");

		if (CollectionUtils.isNotEmpty(subList)) {
			List<Node> childrenNodes = new ArrayList<Node>();
			for (Dictionary subGroup : subList) {
				Long subGroupId = subGroup.getId();
				Node e = this.buildTreeNode(subGroupId, subDictGroupMap, dictGroupMap);
				childrenNodes.add(e);
			}
			node.setChildren(childrenNodes);
		}
		return node;
	}

	/**
	 * 
	 * @Title:根据ID查询字典类别
	 * @Description:
	 * @param id
	 *            字典类别ID
	 * @return
	 * @anthor yixiaoping<thinker163@163.com>
	 * @date 2016年1月23日 下午2:02:58
	 */
	public Dictionary findDictionaryById(Long id) {
		return Dictionary.dao.findById(id);
	}

	/**
	 * 
	 * @Title:根据字典列表编码查询对象
	 * @Description:
	 * @param dictCode
	 *            字典类别编码
	 * @return
	 * @anthor yixiaoping<thinker163@163.com>
	 * @date 2016年1月23日 下午2:03:30
	 */
	public Dictionary findDictionaryByCode(String dictCode) {
		String sql = "select * from config_dictionary where dict_code =?";
		return Dictionary.dao.findFirst(sql, dictCode);
	}
	
	/**
	 * 
	 * @Title:查询某个类别分类下，子列表中优先级最高的值
	 * @Description:
	 * @param pid
	 *            当前字典类别ID
	 * @return
	 * @anthor yixiaoping<thinker163@163.com>
	 * @date 2016年1月23日 下午2:04:22
	 */
	public int findMaxPrioritybyPid(Long pid) {
		String sql = "select max(priority)  as priority from config_dictionary where pid = ? and available = ?";
		Dictionary dictionary = Dictionary.dao.findFirst(sql, pid ,R.Dict.STATUS_AVAILABLE);
		return dictionary.getPriority() == null ? 0 : dictionary.getPriority();
	}
	
	/**
	 * 
	 * @Title:保存字典类别
	 * @Description:
	 * @param dictionary
	 *            字典类别对象
	 * @return
	 * @anthor yixiaoping<thinker163@163.com>
	 * @date 2016年1月23日 下午2:05:34
	 */
	public Dictionary saveDictionary(Dictionary dictionary) {
		Long id = dictionary.getId();
		if (id == null) {
			Long pid = dictionary.getPid();
			int priority = this.findMaxPrioritybyPid(pid) + 1;

			id = Sequence.getSequence();
			dictionary.setId(id);
			dictionary.setAvailable(Integer.valueOf(R.Dict.STATUS_AVAILABLE));
			dictionary.setPriority(priority);
			
			if(dictionary.getDictType() == R.Dict.DICT_FOLDER){
				dictionary.setDictCode(id.toString());
			}
			
			dictionary.save();
		} else {
			Dictionary oldDictionary = Dictionary.dao.findById(id);
			oldDictionary.setDictName(dictionary.getDictName());
			oldDictionary.setDictCode(dictionary.getDictCode());
			dictionary.update();
		}
		return dictionary;
	}
	
	/**
	 * 
	 * @Title:将字典类别对象，构建成JSTREE插件节点对象
	 * @Description:
	 * @param dictionary
	 *            字典类别对象
	 * @return
	 * @anthor yixiaoping<thinker163@163.com>
	 * @date 2016年1月23日 下午2:06:17
	 */
	public Node buildJstreeNode(Dictionary dictionary) {
		Node node = new Node();
		node.setId(dictionary.getId() + "");
		node.setText(dictionary.getDictName());
		node.setType(dictionary.getDictType() + "");
		node.addData("dictCode", dictionary.getDictCode());
		return node;
	}
	
	/**
	 * 
	 * @Title:根据ID删除字典类别
	 * @Description:
	 * @param id
	 *            字典类别ID
	 * @return
	 * @anthor yixiaoping<thinker163@163.com>
	 * @date 2016年1月23日 下午2:07:12
	 */
	public boolean deleteDictionary(Long id) {
		Dictionary dictionary = Dictionary.dao.findById(id);
		dictionary.setAvailable(Integer.valueOf(R.Dict.STATUS_UNAVAILABLE));
		dictionary.update();
		return true;
	}
}
